#include "DbManger.h"

// 饿汉式单例初始化
DbManger* DbManger::dbPtr = new DbManger();

DbManger::DbManger()
{
    // 1. 连接数据库（SQLite）
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("my.db"); // 数据库文件：my.db

    // 2. 打开数据库
    if (!db.open()) {
        qDebug() << "数据库打开失败：" << db.lastError().text();
        return;
    }

    // 3. 创建表（修复原有表结构错误：id 重复定义）
    createTable();
}

DbManger* DbManger::getDbPtr()
{
    return dbPtr;
}

void DbManger::createTable()
{
    // 修复表结构：id 仅需一次定义（自增主键）
    QString sql = R"(
        create table if not exists users(
            id integer primary key autoincrement,
            account varchar(20),
            phone varchar(80),
            department varchar(50),
            status varchar(50),
            startTime datetime
        )
    )";
    QSqlQuery query;
    bool ok = query.exec(sql);
    if (ok) {
        qDebug() << "用户表创建成功";
    } else {
        qDebug() << "用户表创建失败：" << query.lastError().text();
    }
}

// ====================== 查询所有用户 ======================
QVector<QMap<QString, QVariant>> DbManger::queryUsers()
{
    QVector<QMap<QString, QVariant>> users;
    QSqlQuery query("SELECT * FROM users");

    while (query.next()) {
        QMap<QString, QVariant> user;
        user["id"] = query.value("id").toInt();
        user["account"] = query.value("account").toString();
        user["phone"] = query.value("phone").toString();
        user["department"] = query.value("department").toString();
        user["status"] = query.value("status").toString();
        user["startTime"] = query.value("startTime").toDateTime();
        users.append(user);
    }
    return users;
}

// ====================== 新增用户 ======================
bool DbManger::insertUser(const QMap<QString, QVariant>& userData)
{
    QSqlQuery query;
    query.prepare(R"(
        INSERT INTO users(id,account, phone, department, status, startTime)
        VALUES(:id, :account, :phone, :department, :status, :startTime)
    )");
    // 绑定参数（与表字段严格对应）
    query.bindValue(":id", userData["id"].toString());
    query.bindValue(":account", userData["account"].toString());
    query.bindValue(":phone", userData["phone"].toString());
    query.bindValue(":department", userData["department"].toString());
    query.bindValue(":status", userData["status"].toString());
    query.bindValue(":startTime", userData["startTime"].toDateTime());

    if (query.exec()) {
        qDebug() << "用户新增成功";
        return true;
    } else {
        qDebug() << "用户新增失败：" << query.lastError().text();
        return false;
    }
}

// ====================== 更新用户 ======================
bool DbManger::updateUser(int id, const QMap<QString, QVariant>& userData)
{
    QSqlQuery query;
    query.prepare(R"(
        UPDATE users
        SET account=:account, phone=:phone, department=:department, status=:status, startTime=:startTime
        WHERE id=:id
    )");
    // 绑定参数
    query.bindValue(":id", id);
    query.bindValue(":account", userData["account"].toString());
    query.bindValue(":phone", userData["phone"].toString());
    query.bindValue(":department", userData["department"].toString());
    query.bindValue(":status", userData["status"].toString());
    query.bindValue(":startTime", userData["startTime"].toDateTime());

    if (query.exec()) {
        qDebug() << "用户更新成功";
        return true;
    } else {
        qDebug() << "用户更新失败：" << query.lastError().text();
        return false;
    }
}

// ====================== 删除用户 ======================
bool DbManger::deleteUser(int id)
{
    QSqlQuery query;
    query.prepare("DELETE FROM users WHERE id=:id");
    query.bindValue(":id", id);

    if (query.exec()) {
        qDebug() << "用户删除成功";
        return true;
    } else {
        qDebug() << "用户删除失败：" << query.lastError().text();
        return false;
    }
}

QVector<QMap<QString, QVariant> > DbManger::queryDepartments()
{

}

QMap<QString, QVariant> DbManger::getUserById(int id)
{
    QMap<QString, QVariant> user;
       QSqlQuery query;
       query.prepare("SELECT * FROM users WHERE id=:id");
       query.bindValue(":id", id);

       if (query.exec() && query.next()) {
           user["id"] = query.value("id").toInt();
           user["account"] = query.value("account").toString();
           user["phone"] = query.value("phone").toString();
           user["department"] = query.value("department").toString();
           user["status"] = query.value("status").toString();
           user["startTime"] = query.value("startTime").toDateTime();
       }
       return user;
}
